package com.lancoo.answer.util.paperUtils;

import android.content.Context;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;

import androidx.lifecycle.LifecycleOwner;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hanvon.HWCloudManager;
import com.lancoo.answer.model.AnswerConstant;
import com.lancoo.answer.model.ConstantBean;
import com.lancoo.answer.model.TaskState;
import com.lancoo.answer.model.bean.Child;
import com.lancoo.answer.model.bean.ExamViewBean;
import com.lancoo.answer.model.bean.Item;
import com.lancoo.answer.model.bean.ItemAsk;
import com.lancoo.answer.model.bean.ModelAnswerInfo;
import com.lancoo.answer.model.bean.Ques;
import com.lancoo.answer.model.bean.SortIndex;
import com.lancoo.answer.model.bean.Type;
import com.lancoo.answer.model.entity.AnswerSheetBean;
import com.lancoo.answer.model.entity.AnswerSheetChildBean;
import com.lancoo.answer.model.entity.ImgRecognitionCollectionBean;
import com.lancoo.answer.model.entity.IndexBean;
import com.lancoo.answer.model.entity.TaskControlBean;
import com.lancoo.answer.model.entity.TaskOperateBean;
import com.lancoo.answer.model.entity.callabck.ImgRecognitionCallBack;
import com.lancoo.answer.model.eventBean.ImageDownLoadEventBean;
import com.lancoo.answer.model.eventBean.SwitchQuesEventBean;
import com.lancoo.hanvon.GeneralText;
import com.lancoo.hanvon.Tool;
import com.lancoo.hanvon.sdk.SDK_GeneralTextLanguage;
import com.rxjava.rxlife.RxLife;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Single;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import kotlin.Triple;

/**
 * Created by pengmi on 2021/12/22 17:06
 * Description:试题数据二次处理类
 */
public class PaperDataUtils {

    /**
     * 整份试题数据二次加工
     *
     * @param taskOperateBeanList 整份试题结构数据
     * @param queseIndexMap       试题结构原数据存储
     */
    public static void loadPaperData(List<TaskOperateBean> taskOperateBeanList, Map<String, Integer> queseIndexMap) {
        TaskControlBean taskControlBean = ConstantBean.Companion.getTaskControlBean();
        TaskState taskState = ConstantBean.Companion.getTaskState();
        if (taskControlBean == null) {
            return;
        }
        int trainSence = taskControlBean.getTrainSence();
        int paperType = taskControlBean.getPaperType();
        if(paperType==2){
            trainSence=1;
        }
        if (ConstantBean.Companion.getConstantExamBean() == null) {
            return;
        }
        List<Type> kindBeanListk = ConstantBean.Companion.getConstantExamBean().getTypeList();
        if (kindBeanListk == null) {
            return;
        }
        boolean isShowSign=true;
        int typeIndex = 0;//题型递增序号
        for (Type type : kindBeanListk) {
            TaskOperateBean daoyuBean = new TaskOperateBean();
            if (paperType!=3&&taskControlBean.getIsCloseTypeLeader() == 1) {
                daoyuBean.setKindType(0);
                daoyuBean.setQuesIndex(0);
                daoyuBean.setTypeIndex(typeIndex);
                if (type.getQuesList() == null) {
                    continue;
                }
                boolean hasDaoyuFragment=true;
                if(trainSence>=2&&
                        TextUtils.isEmpty(type.getPartMsg())&&
                        TextUtils.isEmpty(type.getTypeLeader())){
                    hasDaoyuFragment=false;
                }

                Ques ques = type.getQuesList().get(0);
                if(!ques.getIsLimitShow()&&!hasDaoyuFragment&&(!TextUtils.isEmpty(ques.getQuesLeader())||
                        !TextUtils.isEmpty(ques.getQuesSectionMsg()))){
                    hasDaoyuFragment=true;
                }
                daoyuBean.setQuesBean(ques);

                if (!ques.getIsLimitShow()&&hasDaoyuFragment) {
                    daoyuBean.setShowSign(isShowSign);
                    isShowSign=false;
                    taskOperateBeanList.add(daoyuBean);
                }

            }

            int quesIndex = 0;//同一题型下大题递增序号
            int totalQuesSize = 0;
            if (type.getQuesList() == null) {
                return;
            }
            for (Ques quesBean : type.getQuesList()) {
                if(type.getQuesList().size()==1){
                    quesBean.setAudioSubLeader("");
                }
                String quesSectionMsg = quesBean.getQuesSectionMsg();
                String quesLeader = quesBean.getQuesLeader()+(quesIndex==0?type.getTypeLeader():"");
                if((paperType==3&&hasText(quesLeader))||!quesBean.getIsLimitShow()&&quesIndex!=0&&(!TextUtils.isEmpty(quesSectionMsg)||
                        !TextUtils.isEmpty(quesLeader))){
                    TaskOperateBean quesIntroduction = new TaskOperateBean();
                    quesIntroduction.setKindType(0);
                    quesIntroduction.setTypeIndex(typeIndex);
                    quesIntroduction.setQuesIndex(quesIndex);
                    quesIntroduction.setQuesBean(quesBean);
                    Log.e("123456",isShowSign+"->"+typeIndex);
                    quesIntroduction.setShowSign(isShowSign&&typeIndex==0);
                    isShowSign=false;
                    taskOperateBeanList.add(quesIntroduction);
                }

                String typeNo = quesBean.getTypeNo();
                if (quesBean.getChildList() == null) {
                    continue;
                }
                for (Child child : quesBean.getChildList()) {
                    if (child.getItemList() == null) {
                        continue;
                    }
                    if (child.getChildAnswerType() == 4) {
                        Item item = child.getItemList().get(0);
                        List<String> imagePathList = item.getImagePathList();
                        String imgRecognitionTxt = item.getImgRecognitionTxt();
                        if (TextUtils.isEmpty(imgRecognitionTxt)) {//如果识别内容为空，需要对图片做特殊处理
                            if (imagePathList != null && imagePathList.size() > 0) {
                                List<ImgRecognitionCollectionBean> list = new ArrayList<>();
                                for (String str : imagePathList) {
                                    ImgRecognitionCollectionBean bean = new ImgRecognitionCollectionBean();
                                    bean.setLocalPath(str);
                                    list.add(bean);
                                    if (str.toLowerCase().startsWith("http") || str.toLowerCase().startsWith("https")) {
                                        //由外部进行图片下载功能
                                        ImageDownLoadEventBean eventBean = new ImageDownLoadEventBean();
                                        eventBean.setImgServicePath(str);
                                        EventBus.getDefault().post(eventBean);
                                    }
                                }
                                item.setImgRecognitionDataList(list);
                            }

                        }
                        if (item.getWrittingAnswerType() == AnswerConstant.ANSWER_TYPE_PICTURE) {
                            if (!TextUtils.isEmpty(item.getStuAnswer()) && TextUtils.isEmpty(item.getImgRecognitionTxt())) {
                                item.setImgRecognitionTxt(item.getStuAnswer());
                                if (taskControlBean.getTrainSence() == 0) {
                                    item.setStuAnswer("");
                                }
                            }
                        }
                    }
                    if (typeNo != null && TextUtils.equals("U", typeNo)) {//改错题item参考答案处理成数字化答案
                        int itemIndex = 0;
                        for (Item item : child.getItemList()) {
                            if (trainSence != 0) {//如果是考试，自动滤掉
                                continue;
                            }
                            List<ModelAnswerInfo> modelAnswerInfoList = quesBean.getModelAnswerInfoList();
                            if (modelAnswerInfoList == null) {
                                continue;
                            }
                            if (modelAnswerInfoList.size() > itemIndex) {
                                ModelAnswerInfo modelAnswerInfo = modelAnswerInfoList.get(itemIndex);
                                String answer = modelAnswerInfo.getAnswer();
                                String itemAnswer = item.getItemAnswer();
                                if (TextUtils.isEmpty(itemAnswer)) {
                                    continue;
                                }
                                if (!itemAnswer.contains("@|")) {//如果参考答案不包含数字化答案，需要处理一下
                                    item.setItemAnswer(answer + "@|" + itemAnswer);
                                }
                            }
                            itemIndex++;
                        }

                    }
                }

                String genreID = quesBean.getGenreID();
                TaskOperateBean taskBean = new TaskOperateBean();
                taskBean.setQuesBean(quesBean);
                taskBean.setQuesIndex(quesIndex);
                taskBean.setKindType(1);
                taskBean.setTypeIndex(typeIndex);
                if (!quesBean.getIsLimitShow()) {
                    taskOperateBeanList.add(taskBean);
                }

                if (!TextUtils.isEmpty("genreID") &&
                        taskState == TaskState.LOOKING && TextUtils.equals("VD", genreID)) {//如果是查看评阅下的词汇拼写，只加载一个结果界面
                    break;
                }
                List<Child> childList = quesBean.getChildList();
                if (quesBean.getTypeNo() == null || quesBean.getGenreID() == null) {
                    continue;
                }
                if (childList == null) {
                    break;
                }

                switch (quesBean.getGenreID()) {
                    case "20"://选词填空
                        for (Child child : childList) {
                            if (child.getItemList() == null) {
                                continue;
                            }
                            totalQuesSize += child.getItemList().size();
                        }
                        break;
                    default:
                        switch (quesBean.getTypeNo()) {
                            case "m"://匹配题
                            case "P"://阅读匹配
                            case "S"://听力填空
                            case "U"://改错题
                                for (Child child : childList) {
                                    if (child.getItemList() == null) {
                                        continue;
                                    }
                                    totalQuesSize += child.getItemList().size();  //特殊题型，根据答题点统计小题数
                                }
                                break;
                            default:
                                totalQuesSize += childList.size();
                        }
                }


                int subChildIndex = 0;//同一大题下小题递增序号
                for (Child ignored : childList) {
                    if (!quesBean.getIsLimitShow()) {
                        queseIndexMap.put(typeIndex + "" + quesIndex + "" + subChildIndex, taskOperateBeanList.size() - 1);
                    }
                    subChildIndex++;
                }
                quesIndex++;
            }
            daoyuBean.setTotalQueseCount(totalQuesSize);
            typeIndex++;
        }
    }

    /**
     * 答题卡数据结构构造
     *
     * @param answerSheetBeanList 答题卡数据模型List
     * @param currentTypeIndex    传入的TypeIndex
     * @param currentQuesIndex    传入的TypeIndex
     * @param currentChildIndex   传入的TypeIndex
     * @param currentItemIdex     传入的TypeIndex
     * @return Triple
     */
    public static Triple<Integer, Integer, Integer> loadAnswerSheetData(List<AnswerSheetBean> answerSheetBeanList,
                                                                        int currentTypeIndex, int currentQuesIndex,
                                                                        int currentChildIndex, int currentItemIdex,int kindType) {
        Log.e("eeee","kindType:"+kindType);
        int sortIndex = 1;//试题总个数
        int typeIndex = 0;
        int quesIndex;
        int childIndex;
        int itemIndex;
        int scrollIndex = 0;//小题滚动下标
        int unAnswerCount = 0;//未作答小题数

        ExamViewBean constantExamBean = ConstantBean.Companion.getConstantExamBean();
        TaskControlBean taskControlBean = ConstantBean.Companion.getTaskControlBean();

        if (taskControlBean == null) {
            return new Triple<>(0, 0, 0);
        }
        if (constantExamBean == null) {
            return new Triple<>(0, 0, 0);
        }
        int trainSence = taskControlBean.getTrainSence();
        int paperType = taskControlBean.getPaperType();
        if(paperType==2){
            trainSence=1;
        }
        List<Type> typeList = constantExamBean.getTypeList();
        if (typeList == null) {
            return new Triple<>(0, 0, 0);
        }
        ConstantBean.Companion.getConstantExamBean().getTypeList();
        for (Type type : typeList) {//遍历题型
            if (type == null) {
                continue;
            }
            quesIndex = 0;
            List<AnswerSheetChildBean> list = new ArrayList<>();
            float totalScore = 0f;
            float answerScore = 0f;
            if (type.getQuesList() == null) {
                continue;
            }
            for (Ques ques : type.getQuesList()) {//遍历大题
                childIndex = 0;
                String typeNo = ques.getTypeNo();
                if(paperType==3){
                    list=new ArrayList<>();
                }
                if (ques.getChildList() == null) {
                    continue;
                }
                for (Child child : ques.getChildList()) {
                    itemIndex = 0;
                    if(TextUtils.equals(ques.getGenreID(),"52")){
                        if(currentTypeIndex==typeIndex&&currentQuesIndex==quesIndex&&currentChildIndex==childIndex){
                            itemIndex=child.getSelectedItemIndex();
                            currentItemIdex=child.getSelectedItemIndex();
                        }
                    }
                    if (typeNo == null) {
                        continue;
                    }
                    String sortIndexType = child.getSortIndexType();
                    if (sortIndexType == null) {
                        continue;
                    }
                    if (TextUtils.equals(sortIndexType, "1")) {
                        for (Item item : child.getItemList()) {
                            Child child1 = new Child();
                            totalScore += item.getTotalScore();
                            if (item.getEvalScore() > 0) {
                                answerScore += item.getEvalScore();
                            }
                            List<Item> itemList = new ArrayList<>();
                            itemList.add(item);
                            child1.setItemList(itemList);
                            AnswerSheetChildBean bean =
                                    buildAnswerSheetChildBean(item.getSortIndex(), typeIndex, quesIndex, childIndex,
                                            itemIndex, child1, currentTypeIndex, currentQuesIndex,
                                            currentChildIndex, currentItemIdex);
                            if (ques.getIsLimitShow()) {

                                bean.setShowState(bean.getShowState() == 0 ? 5 : 6);
                            }
                            list.add(bean);
                            if (bean.getIsSelected() == 1) {
                                scrollIndex = answerSheetBeanList.size();
                            }
                            if (bean.getShowState() == 0) {
                                unAnswerCount++;
                            }
                            if(kindType==0){
                                bean.setIsSelected(0);
                            }
                            sortIndex++;
                            itemIndex++;
                        }
                    } else {
                        String sortPosition = child.getItemList().get(0).getSortIndex();
                        AnswerSheetChildBean bean;
                        if(TextUtils.equals(ques.getGenreID(),"52")){
                            itemIndex=child.getSelectedItemIndex();
                            Child child1=new Child();
                            List<Item> itemList=new ArrayList<>();
                            itemList.add(child.getItemList().get(child.getSelectedItemIndex()));
                            child1.setItemList(itemList);
                            bean = buildAnswerSheetChildBean(sortPosition, typeIndex,
                                    quesIndex, childIndex, itemIndex, child1, currentTypeIndex, currentQuesIndex,
                                    currentChildIndex, currentItemIdex);
                        }else{
                            bean = buildAnswerSheetChildBean(sortPosition, typeIndex,
                                    quesIndex, childIndex, itemIndex, child, currentTypeIndex, currentQuesIndex,
                                    currentChildIndex, currentItemIdex);
                        }
                        if (ques.getIsLimitShow()) {
                            bean.setShowState(bean.getShowState() == 0 ? 5 : 6);
                        }

                        list.add(bean);
                        if (bean.getIsSelected() == 1) {
                            scrollIndex = answerSheetBeanList.size();
                        }
                        if (bean.getShowState() == 0) {
                            unAnswerCount++;
                        }
                        if(kindType==0){
                            bean.setIsSelected(0);
                        }
                        float currentChildScore=0f;
                        for (Item item : child.getItemList()) {
                            totalScore += item.getTotalScore();
                            if (item.getEvalScore() > 0) {
                                answerScore += item.getEvalScore();
                                currentChildScore += item.getEvalScore();
                            }
                        }
                        //翻译选择特殊处理
                        if(bean.getShowState()==2&&TextUtils.equals(ques.getGenreID(),"14")){
                            if(currentChildScore>0){
                                bean.setShowState(3);
                            }
                        }
                        sortIndex++;
                    }
                    childIndex++;
                }

                if(paperType==3){//如果是导入试题，一个ques，一个单元
                    AnswerSheetBean answerSheetBean = new AnswerSheetBean();
                    answerSheetBean.setPartMsg(type.getPartMsg());
                    answerSheetBean.setSectionMsg(type.getSectionMsg());
                    answerSheetBean.setTypeIndex(type.getTypeIndex());
                    answerSheetBean.setIndex(typeIndex);
                    String leaderStr = (quesIndex==0?type.getTypeLeader():"")+ques.getQuesLeader();
                    answerSheetBean.setKindTypeName(leaderStr);
                    answerSheetBean.setTotalScore(DecimalFormatUtils.RoundToTheNearestDecimalPlace1(totalScore));
                    answerSheetBean.setAnswerScore(DecimalFormatUtils.RoundToTheNearestDecimalPlace1(answerScore));
                    answerSheetBean.setPassed(totalScore * 0.6 <= answerScore);
                    answerSheetBean.setAnswerSheetChildBeanList(list);
                    if(hasText(leaderStr)){

                        answerSheetBeanList.add(answerSheetBean);
                    }else{
                        if(answerSheetBeanList.size()!=0){
                            AnswerSheetBean lastBean = answerSheetBeanList.get(answerSheetBeanList.size() - 1);
                            if(lastBean.getIndex()==typeIndex){
                                List<AnswerSheetChildBean> answerSheetChildBeanList = lastBean.getAnswerSheetChildBeanList();
                                answerSheetChildBeanList.addAll(list);
                                lastBean.setAnswerSheetChildBeanList(answerSheetChildBeanList);
                            }else{
                                answerSheetBeanList.add(answerSheetBean);
                            }
                        }else{
                            answerSheetBeanList.add(answerSheetBean);
                        }
                    }
                    totalScore=0;
                    answerScore=0;
                }

                quesIndex++;

            }
            if(paperType!=3){
                AnswerSheetBean answerSheetBean = new AnswerSheetBean();
                answerSheetBean.setTypeIndex(type.getTypeIndex());
                answerSheetBean.setPartMsg(type.getPartMsg());
                answerSheetBean.setSectionMsg(type.getSectionMsg());
                String name = type.getOtherName();

                if (TextUtils.isEmpty(name)) {
                    name = type.getGenreName();
                }
                if (TextUtils.isEmpty(name)) {
                    name = type.getTypeName();
                }
                if(ConstantBean.Companion.getTaskControlBean().getPaperType()==3){
                    answerSheetBean.setKindTypeName(type.getTypeLeader());
                }else{
                    answerSheetBean.setKindTypeName(TextUtils.isEmpty(name) ? "" : name);
                }

                answerSheetBean.setTotalScore(DecimalFormatUtils.RoundToTheNearestDecimalPlace1(totalScore));
                answerSheetBean.setAnswerScore(DecimalFormatUtils.RoundToTheNearestDecimalPlace1(answerScore));
                answerSheetBean.setPassed(totalScore * 0.6 <= answerScore);
                answerSheetBean.setAnswerSheetChildBeanList(list);
                if(trainSence==3){
                    if(!TextUtils.isEmpty(type.getPartMsg())){
                        answerSheetBeanList.add(answerSheetBean);
                    }else{
                        if(answerSheetBeanList.size()!=0){
                            AnswerSheetBean lastBean = answerSheetBeanList.get(answerSheetBeanList.size() - 1);
                            List<AnswerSheetChildBean> answerSheetChildBeanList = lastBean.getAnswerSheetChildBeanList();
                            answerSheetChildBeanList.addAll(list);
                            lastBean.setAnswerSheetChildBeanList(answerSheetChildBeanList);
                        }else{
                            answerSheetBeanList.add(answerSheetBean);
                        }
                    }

                }else{
                    answerSheetBeanList.add(answerSheetBean);
                }
            }
            typeIndex++;
        }
        return new Triple(scrollIndex, unAnswerCount, sortIndex - 1);
    }


    public static List<AnswerSheetBean> loadAnswerSheetData(List<Type> list) {
        return loadAnswerSheetData(list, TaskState.TRAINING);

    }

    public static List<AnswerSheetBean> loadAnswerSheetData(List<Type> list, TaskState taskState) {
        ExamViewBean constantExamBean = new ExamViewBean();
        constantExamBean.setTypeList(list);
        ConstantBean.Companion.setConstantExamBean(constantExamBean);
        ConstantBean.Companion.setTaskState(taskState);
        List<AnswerSheetBean> answerSheetBeanList = new ArrayList<>();
        loadAnswerSheetData(answerSheetBeanList, -1, -1, -1, -1,1);
        return answerSheetBeanList;

    }


    /**
     * 创建答题卡数据
     * @param sortIndex
     * @param typeIndex
     * @param quesIndex
     * @param childIndex
     * @param itemIndex
     * @param child
     * @param currentTypeIndex
     * @param currentQuesIndex
     * @param currentChildIndex
     * @param currentItemIdex
     * @return
     */
    private static AnswerSheetChildBean buildAnswerSheetChildBean(String sortIndex,
                                                                  int typeIndex, int quesIndex, int childIndex, int itemIndex, Child child,
                                                                  int currentTypeIndex, int currentQuesIndex,
                                                                  int currentChildIndex, int currentItemIdex) {
        AnswerSheetChildBean bean = new AnswerSheetChildBean();
        bean.setSortIndex(sortIndex + "");
        bean.setTypeIndex(typeIndex);
        bean.setQuesIndex(quesIndex);
        bean.setChildIndex(childIndex);
        bean.setItemIndex(itemIndex);
        boolean isSelected = typeIndex == currentTypeIndex &&
                quesIndex == currentQuesIndex &&
                childIndex == currentChildIndex &&
                itemIndex == currentItemIdex;
        bean.setIsSelected(isSelected ? 1 : 0);
        boolean hasAnswer = false;
        List<Item> itemList = child.getItemList();
        float scoreRate = 0f;
        float totalAnswerScore = 0f;
        if(ConstantBean.getTaskState() == TaskState.TRAINING&&itemList.get(0).getItemMark()){
            bean.setMark(true);
        }
        if (itemList != null) {
            for (Item item : itemList) {
                scoreRate += item.getScoreRate();
                totalAnswerScore += item.getEvalScore();
                int writtingAnswerType = item.getWrittingAnswerType();
                if (writtingAnswerType == AnswerConstant.ANSWER_TYPE_PICTURE) {
                    if (item.getImagePathList() != null && item.getImagePathList().size() > 0 &&
                            !TextUtils.isEmpty(item.getImagePathList().get(0))) {
                        hasAnswer = true;
                    }
                    if(item.getImageAnswer() != null && !item.getImageAnswer().isEmpty()){
                        hasAnswer = true;
                    }
                    if (!TextUtils.isEmpty(item.getImgRecognitionTxt())) {
                        hasAnswer = true;
                    }
                } else if (writtingAnswerType == AnswerConstant.ANSWER_TYPE_VIDEO) {
                    if (!TextUtils.isEmpty(item.getVideoPath())) {
                        hasAnswer = true;
                    }
                } else {
                    if (!TextUtils.isEmpty(item.getStuAnswer())) {
                        hasAnswer = true;
                    }
                    if (!TextUtils.isEmpty(item.getAudioPath())) {
                        hasAnswer = true;
                    }
                    if (item.getRecordAnswer() != null) {
                        hasAnswer = true;
                    }
                    if (!TextUtils.isEmpty(item.getAudioLocalPath())) {
                        hasAnswer = true;
                    }
                }

                if(!TextUtils.isEmpty(item.getScanImagePath())){
                    hasAnswer=true;
                }

            }
        }
        if (ConstantBean.Companion.getTaskControlBean().isHp()) {
            Item item = child.getItemList().get(0);
            if (item.getMutEvaluateScore() < 0) {
                bean.setShowState(4);
            } else {
                if (item.getMutEvaluateScore() >= 0.6 * item.getTotalScore()) {
                    bean.setShowState(3);
                } else {
                    bean.setShowState(2);
                }

            }
        } else {
            if (ConstantBean.getTaskState() == TaskState.LOOKING) {
                if (totalAnswerScore < 0) {
                    bean.setShowState(4);
                } else {
                    bean.setShowState(scoreRate / itemList.size() >= 0.6 ? 3 : 2);
                }

            } else {
                bean.setShowState(hasAnswer ? 1 : 0);
            }
        }
        return bean;
    }



    /**
     * 作弊作答
     */
    public static void zuobi() {
        if (ConstantBean.Companion.getConstantExamBean() == null) {
            return;
        }
        if (ConstantBean.Companion.getTaskState() != TaskState.TRAINING) {
            return;
        }
        if (ConstantBean.Companion.getTaskControlBean().getEnableAnwer() == 0) {
            return;
        }
        if (!ConstantBean.Companion.getTaskControlBean().isOpenZuobiAnswer()) {
            return;
        }
        List<Type> typeList = ConstantBean.Companion.getConstantExamBean().getTypeList();
        for (Type type : typeList) {
            if (type.getQuesList() == null) {
                continue;
            }
            for (Ques ques : type.getQuesList()) {
                String typeNo = ques.getTypeNo();
                if (ques.getChildList() == null) {
                    continue;
                }
                for (Child child : ques.getChildList()) {
                    if (child.getItemList() == null) {
                        continue;
                    }
                    int itemIndex = 0;
                    for (Item item : child.getItemList()) {
                        if (item.getStuAnswer() == null || TextUtils.isEmpty(item.getStuAnswer())) {
                            String itemAnswer = item.getItemAnswer();
                            if (itemAnswer == null) {
                                continue;
                            }
                            if (typeNo != null && TextUtils.equals("U", typeNo)) {//改错题特殊处理
                                List<ModelAnswerInfo> modelAnswerInfoList = ques.getModelAnswerInfoList();
                                if (modelAnswerInfoList.size() > itemIndex) {
                                    ModelAnswerInfo modelAnswerInfo = modelAnswerInfoList.get(itemIndex);
                                    String answer = modelAnswerInfo.getAnswer();
                                    Log.e("zuobi","参考答案"+item.getItemAnswer());
                                    if(itemAnswer.contains("$/")){
                                        String[] split = itemAnswer.split("\\$/");
                                        String s = split[split.length - 1];

                                        if (answer.contains("$|")) {

                                            item.setStuAnswer(answer.split("\\$\\|")[0] + "@|" + s);
                                        }else{
                                            item.setStuAnswer(answer + "@|" + s);
                                        }
                                    } else if (answer.contains("$|")) {
                                        if(itemAnswer.contains(answer.split("\\$\\|")[0])){
                                            item.setStuAnswer(itemAnswer.split("\\$\\|")[1]);
                                        }else{
                                            item.setStuAnswer(answer.split("\\$\\|")[0] + "@|" + itemAnswer);
                                        }

                                    } else {
                                        if(itemAnswer.contains(answer)){
                                            item.setStuAnswer(itemAnswer);
                                        }else{
                                            item.setStuAnswer(answer + "@|" + itemAnswer);
                                        }

                                    }
                                }
                                itemIndex++;
                                continue;
                            }
                            if (TextUtils.equals(child.getChildAnswerType() + "", "2")) {
                                if (itemAnswer.contains("$/")) {
                                    item.setStuAnswer(Html.fromHtml(itemAnswer.split("\\$/")[0]).toString());
                                } else {
                                    item.setStuAnswer(Html.fromHtml(itemAnswer).toString());
                                }
                            } else {
                                if (TextUtils.equals("f", ques.getTypeNo())) {//作文题特殊判断
                                    String audioPath = item.getAudioPath();
                                    String videoPath = item.getVideoPath();
                                    List<String> imagePathList = item.getImagePathList();
                                    if (TextUtils.isEmpty(audioPath)
                                            && item.getRecordAnswer() == null
                                            && TextUtils.isEmpty(videoPath)
                                            && (imagePathList == null || imagePathList.size() == 0)
                                            && (item.getImageAnswer() == null || item.getImageAnswer().isEmpty())) {
                                        item.setStuAnswer(Html.fromHtml(itemAnswer).toString());
                                    }
                                } else {
                                    item.setStuAnswer(Html.fromHtml(itemAnswer).toString());
                                }

                            }
                            List<ItemAsk> itemAskList = item.getItemAskList();
                            if (itemAskList == null) {
                                continue;
                            }
                            for (ItemAsk itemAsk : itemAskList) {
                                itemAsk.setStuAnswer(Html.fromHtml(itemAsk.getAnswer()).toString());
                            }

                        }
                    }
                }
            }
        }
    }

    /**
     * 获取小题未作答个数
     *
     * @return Triple
     */
    public static int getUnAnswerCount() {
        int unAnswerCount = 0;//未作答小题数
        for (Type testItem : ConstantBean.Companion.getConstantExamBean().getTypeList()) {//遍历题型
            if (testItem.getQuesList() == null) {
                continue;
            }
            for (Ques ques : testItem.getQuesList()) {//遍历大题
                String typeNo = ques.getTypeNo();
                String genreID = ques.getGenreID();
                if (ques.getChildList() == null) {
                    continue;
                }
                for (Child child : ques.getChildList()) {
                    if (typeNo == null) {
                        continue;
                    }
                    switch (typeNo) {
                        case "m"://匹配题
                        case "P"://阅读匹配
                        case "S"://听力填空
                        case "U"://改错题
                            if (child.getItemList() == null) {
                                break;
                            }
                            for (Item item : child.getItemList()) {
                                Child child1 = new Child();
                                List<Item> itemList = new ArrayList<>();
                                itemList.add(item);
                                child1.setItemList(itemList);
                                AnswerSheetChildBean bean = buildAnswerSheetChildBean("", 0,
                                        0, 0, 0, child1, 0, 0,
                                        0, 0);
                                if (bean.getShowState() == 0) {
                                    unAnswerCount++;
                                }
                            }
                            break;
                        default:
                            AnswerSheetChildBean bean = buildAnswerSheetChildBean("", 0,
                                    0, 0, 0, child, 0, 0,
                                    0, 0);
                            if (bean.getShowState() == 0) {
                                unAnswerCount++;
                            }
                    }
                }
            }
        }
        return unAnswerCount;
    }

    public static Pair<Integer,Integer> getAnswerCount() {
        int unAnswerCount = 0;//未作答小题数
        int totalCount=0;//总的小题数
        for (Type testItem : ConstantBean.Companion.getConstantExamBean().getTypeList()) {//遍历题型
            if (testItem.getQuesList() == null) {
                continue;
            }
            for (Ques ques : testItem.getQuesList()) {//遍历大题
                String typeNo = ques.getTypeNo();
                String genreID = ques.getGenreID();
                if (ques.getChildList() == null) {
                    continue;
                }
                for (Child child : ques.getChildList()) {
                    String sortIndexType = child.getSortIndexType();
                    if (typeNo == null) {
                        continue;
                    }
                    if(TextUtils.equals(sortIndexType,"0")){
                        AnswerSheetChildBean bean = buildAnswerSheetChildBean("", 0,
                                0, 0, 0, child, 0, 0,
                                0, 0);
                        if (bean.getShowState() == 0) {
                            unAnswerCount++;
                        }
                        totalCount++;
                    }else{
                        if (child.getItemList() == null) {
                            break;
                        }
                        for (Item item : child.getItemList()) {
                            Child child1 = new Child();
                            List<Item> itemList = new ArrayList<>();
                            itemList.add(item);
                            child1.setItemList(itemList);
                            AnswerSheetChildBean bean = buildAnswerSheetChildBean("", 0,
                                    0, 0, 0, child1, 0, 0,
                                    0, 0);
                            if (bean.getShowState() == 0) {
                                unAnswerCount++;
                            }
                            totalCount++;
                        }
                    }
                }
            }
        }
        return new Pair<>(totalCount,unAnswerCount);
    }


    /**
     * 判断最后一个小题是否作答完
     *
     * @return Triple
     */
    public static boolean isAnswerForLastChild() {
        int unAnswerCount = 0;//未作答小题数
        ExamViewBean constantExamBean = ConstantBean.Companion.getConstantExamBean();
        if(constantExamBean==null){
            return false;
        }
        List<Type> typeList = constantExamBean.getTypeList();
        if(typeList==null){
            return false;
        }
        Type type = typeList.get(typeList.size() - 1);
        List<Ques> quesList = type.getQuesList();
        if(quesList==null){
            return false;
        }
        Ques ques = quesList.get(quesList.size() - 1);
        List<Child> childList = ques.getChildList();
        if(childList==null){
            return false;
        }
        Child child = childList.get(childList.size() - 1);
        int childAnswerType = child.getChildAnswerType();
        if(childAnswerType==2||childAnswerType==4){
            return false;
        }
        String typeNo = ques.getTypeNo();
        String genreID = ques.getGenreID();
        if (typeNo == null) {
            return false;
        }
        switch (typeNo) {
            case "m"://匹配题
            case "P"://阅读匹配
            case "S"://听力填空
            case "U"://改错题
                if (child.getItemList() == null) {
                    break;
                }
                for (Item item : child.getItemList()) {
                    Child child1 = new Child();
                    List<Item> itemList = new ArrayList<>();
                    itemList.add(item);
                    child1.setItemList(itemList);
                    AnswerSheetChildBean bean = buildAnswerSheetChildBean("", 0,
                            0, 0, 0, child1, 0, 0,
                            0, 0);
                    if (bean.getShowState() == 0) {
                        unAnswerCount++;
                    }
                }
                break;
            default:
                AnswerSheetChildBean bean = buildAnswerSheetChildBean("", 0,
                        0, 0, 0, child, 0, 0,
                        0, 0);
                if (bean.getShowState() == 0) {
                    unAnswerCount++;
                }
        }
        return unAnswerCount==0;
    }

    public static Pair<Integer, Integer> getSortQuesIndexAndChildIndexFromZero(IndexBean indexBean) {
        return getSortQuesIndexAndChildIndexFromZero(indexBean.getTypeIndex(), indexBean.getQuesIndex(),
                indexBean.getChildIndex(), indexBean.getItemIndex());
    }

    /**
     * 根据题型下标，大题下标，小题下标，答题点下标获取整份试题下的大题下标以及当前大题下的小题下标
     *
     * @param typeIndex  题型下标
     * @param quesIndex  大题下标
     * @param childIndex 小题下标
     * @param itemIndex  答题点下标
     * @return quesSortIndex-整份试题下的大题下标（从0开始），currentQuesChildIndex-当前ques下的小题下标（从0开始）
     */
    public static Pair<Integer, Integer> getSortQuesIndexAndChildIndexFromZero(int typeIndex, int quesIndex,
                                                                               int childIndex, int itemIndex) {
        int quesSortIndex = 0;
        int currentQuesChildIndex = 0;
        ExamViewBean constantExamBean = ConstantBean.Companion.getConstantExamBean();
        if (constantExamBean == null) {
            return new Pair<>(quesIndex, currentQuesChildIndex);
        }
        List<Type> typeList = constantExamBean.getTypeList();
        if (typeList == null) {
            return new Pair<>(quesIndex, currentQuesChildIndex);
        }
        for (int i = 0; i < typeList.size(); i++) {
            Type type = typeList.get(i);
            List<Ques> quesList = type.getQuesList();
            if (quesList == null) {
                break;
            }
            int currentQuesIndex = 0;
            for (int j = 0; j < quesList.size(); j++) {
                Ques ques = quesList.get(j);
                List<Child> childList = ques.getChildList();
                if (childList == null) {
                    break;
                }
                currentQuesIndex = j;
                if (typeIndex == i && quesIndex == j) {
                    String typeNo = ques.getTypeNo();
                    switch (typeNo) {
                        case "m"://匹配题
                        case "P"://阅读匹配
                        case "S"://听力填空
                        case "U"://改错题
                            currentQuesChildIndex = itemIndex;
                            break;
                        default:
                            currentQuesChildIndex = childIndex;
                    }
                    break;
                }
                quesSortIndex++;
            }
            if (typeIndex == i && quesIndex == currentQuesIndex) {
                break;
            }
        }
        return new Pair<>(quesSortIndex, currentQuesChildIndex);
    }

    /**
     * 根据整份试题下的大题下标以及当前大题下的小题下标获取题型下标，大题下标，小题下标，答题点下标
     *
     * @param quesSortIndex         整份试题下的大题下标（从0开始）
     * @param currentQuesChildIndex currentQuesChildIndex-当前大题下的小题下标（从0开始）
     * @return IndexBean
     */
    public static IndexBean getRealIndex(int quesSortIndex, int currentQuesChildIndex, List<? extends Type> typeList) {
        IndexBean indexBean = new IndexBean();
        int typeIndex = 0;
        int quesIndex = 0;
        int childIndex = 0;
        int itemIndex = 0;
        int quesAddIndex = 0;
        if (typeList == null) {
            return indexBean;
        }
        for (int i = 0; i < typeList.size(); i++) {
            typeIndex = i;
            Type type = typeList.get(i);
            List<Ques> quesList = type.getQuesList();
            if (quesList == null) {
                break;
            }
            for (int j = 0; j < quesList.size(); j++) {
                quesIndex = j;
                Ques ques = quesList.get(j);
                List<Child> childList = ques.getChildList();
                if (childList == null) {
                    break;
                }
                if (quesAddIndex == quesSortIndex) {
                    String typeNo = ques.getTypeNo();
                    switch (typeNo) {
                        case "m"://匹配题
                        case "P"://阅读匹配
                        case "S"://听力填空
                        case "U"://改错题
                            childIndex = 0;
                            itemIndex = currentQuesChildIndex;
                            break;
                        default:
                            itemIndex = 0;
                            childIndex = currentQuesChildIndex;
                    }
                    quesAddIndex++;
                    break;
                }
                quesAddIndex++;
            }
            if (quesAddIndex > quesSortIndex) {
                break;
            }
        }
        indexBean.setTypeIndex(typeIndex);
        indexBean.setQuesIndex(quesIndex);
        indexBean.setChildIndex(childIndex);
        indexBean.setItemIndex(itemIndex);
        return indexBean;
    }

    /**
     * 判断是否是有效下标 考试专用
     *
     * @param callbackBean 回调获取的bean
     * @param realBean     真实下标bean
     * @return boolean
     */
    public static boolean isRightIndex(SwitchQuesEventBean callbackBean, IndexBean realBean) {
        return callbackBean.getTypeIndex() == realBean.getTypeIndex()
                && callbackBean.getQuesIndex() == realBean.getQuesIndex()
                && callbackBean.getChildIndex() == realBean.getChildIndex();
    }

    /**
     * 根据currentPageIndex获取typeList的真实下标 暂时考辅专用
     *
     * @param currentPageIndex 试题试题页下标
     * @param typeList
     * @return
     */
    public static IndexBean getRealIndex(int currentPageIndex, List<Type> typeList) {
        IndexBean indexBean = new IndexBean();
        if (typeList == null) {
            return indexBean;
        }
        int pagerIndex = 0;
        int typeIndex = 0;
        int quesIndex = 0;
        boolean isLead = false;
        boolean isreturn = false;
        for (Type type : typeList) {
            int i = 0;
            quesIndex = 0;
            for (Ques ques : type.getQuesList()) {
                if (i == 0) {
                    if (currentPageIndex == pagerIndex) {
                        isreturn = true;
                        isLead = true;
                        break;
                    }
                    pagerIndex++;
                }
                i++;
                isLead = false;
                if (currentPageIndex == pagerIndex) {
                    isreturn = true;
                    break;
                }
                pagerIndex++;
                quesIndex++;
            }
            if (isreturn) {
                break;
            }
            typeIndex++;
        }

        indexBean.setTypeIndex(typeIndex);
        indexBean.setChildIndex(0);
        indexBean.setItemIndex(0);
        indexBean.setQuesIndex(quesIndex);
        indexBean.setLeadPage(isLead);
        return indexBean;
    }


    /**
     * 重新构造结果结果答题卡SortIndexList数据
     *
     * @param typeList list
     */
    public static void rebuildSortIndexListData(List<Type> typeList) {

        for (Type type : typeList) {

            for (Ques ques : type.getQuesList()) {

                List<SortIndex> sortIndexList = new ArrayList<>();
                for (Child child : ques.getChildList()) {

                    String sortIndexType = child.getSortIndexType();
                    boolean hasNoScore = false;
                    if (TextUtils.equals(sortIndexType, "0")) {
                        SortIndex sortIndex = new SortIndex();
                        float scoreRate = 0f;
                        float answerScore = 0f;
                        for (Item item : child.getItemList()) {
                            scoreRate += item.getScoreRate();
                            if (item.getEvalScore() < 0) {
                                sortIndex.setState(0);
                                hasNoScore = true;
                            } else {
                                sortIndex.setState(2);
                                answerScore += item.getEvalScore();
                            }
                        }
                        sortIndex.setNewSortIndex(child.getItemList().get(0).getSortIndex());
                        sortIndex.setScoreRate((double) (scoreRate / child.getItemList().size()));
                        sortIndex.setScore(answerScore + "");
                        sortIndex.setState(hasNoScore ? 0 : 2);
                        sortIndexList.add(sortIndex);
                    } else {
                        for (Item item : child.getItemList()) {
                            SortIndex sortIndex = new SortIndex();
                            sortIndex.setNewSortIndex(item.getSortIndex());
                            if (item.getEvalScore() < 0) {
                                sortIndex.setState(0);
                                sortIndex.setScore("0");
                            } else {
                                sortIndex.setState(2);
                                sortIndex.setScore(item.getEvalScore() + "");
                            }
                            sortIndex.setScoreRate((double) item.getScoreRate());
                            sortIndexList.add(sortIndex);
                        }
                    }
                }
                ques.setSortIndexList(sortIndexList);
            }

        }
    }

    /**
     * 收集到的图片信息待识别 (识别流程与界面生命周期绑定，界面销毁，识别会中断)
     */
    public static void collectionImgsToRecognition(final Context mContext, final ImgRecognitionCallBack callBack) {
        if (callBack == null) {
            return;
        }
        final long startTime = System.currentTimeMillis();

        Observable.create((ObservableOnSubscribe<String>) emitter -> {
                    ExamViewBean constantExamBean = ConstantBean.Companion.getConstantExamBean();
                    if (constantExamBean == null) {
                        return;
                    }
                    List<Type> typeList = constantExamBean.getTypeList();
                    if (typeList == null) {
                        return;
                    }
                    HWCloudManager hwCloudManagerGeneralText = new HWCloudManager(mContext,
                            "3e1e4e36-5763-4353-9562-539ddf2bf14d") {
                        @Override
                        public String generateID() {
                            return "GT2021";
                        }

                        @Override
                        public String generalTextLanguage(String isText, String picPath) {// 优化超时时长，原SDK10秒钟太短了
                            String androidKey = Tool.findFieldValueOfHWCloudManager(this, "androidKey");
                            String whitelist = Tool.findFieldValueOfHWCloudManager(this, "whitelist");
                            return SDK_GeneralTextLanguage.GeneralTextDiscern(isText, picPath, androidKey, whitelist);
                        }
                    };
                    int typeIndex = 0;
                    for (Type type : typeList) {
                        int quesIndex = 0;
                        for (Ques ques : type.getQuesList()) {
                            int childIndex = 0;
                            for (Child child : ques.getChildList()) {
                                for (Item item : child.getItemList()) {
                                    List<ImgRecognitionCollectionBean> imgRecognitionDataList = item.getImgRecognitionDataList();
                                    StringBuffer recognitionStringBuffer = new StringBuffer();
                                    if (imgRecognitionDataList == null) {
                                        continue;
                                    }
                                    for (int i = 0; i < imgRecognitionDataList.size(); i++) {
                                        String path = imgRecognitionDataList.get(i).getLocalPath();
                                        String lowerPath = path.toLowerCase();
                                        if (lowerPath.startsWith("http") || lowerPath.startsWith("https")) {//网络路径
                                            String s = ConstantBean.Companion.getImgsLocalPathMap().get(lowerPath);
                                            if (s != null) {
                                                path = s;
                                            }else{
                                                Map<String, String> imgsLocalPathMap = ConstantBean.Companion.getImgsLocalPathMap();
                                                Set<Map.Entry<String, String>> entries = imgsLocalPathMap.entrySet();
                                                Iterator<Map.Entry<String, String>> iterator = entries.iterator();
                                                while (iterator.hasNext()){
                                                    Map.Entry<String, String> next = iterator.next();
                                                    if(TextUtils.equals(path,next.getKey())){
                                                        path=next.getValue();
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                        String result = hwCloudManagerGeneralText.generalTextLanguage("0", path);
                                        if (result == null) {
                                            result = "";
                                        }
                                        GeneralText.Result result1 = null;
                                        try {
                                            result1 = new Gson().fromJson(result, GeneralText.Result.class);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                        String content = "";
                                        if (result1 != null) {
                                            content = result1.get();//识别内容
                                        }
                                        if (!TextUtils.isEmpty(recognitionStringBuffer.toString())) {
                                            recognitionStringBuffer.append(" ");
                                        }
                                        if (!TextUtils.isEmpty(content)) {
                                            recognitionStringBuffer.append(content);
                                        }
                                        imgRecognitionDataList.get(i).setRecognitionContent(content);

                                    }
                                    item.setImgRecognitionDataList(imgRecognitionDataList);
                                    item.setImgRecognitionTxt(recognitionStringBuffer.toString());
                                }
                                childIndex++;
                            }
                            quesIndex++;
                        }
                        typeIndex++;
                    }
                    emitter.onNext("");
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .as(RxLife.as((LifecycleOwner) mContext))
                .subscribe(result -> {

                    final long endTime = System.currentTimeMillis() - startTime;
                    callBack.onSuccess();
                }, error -> {
                    final long endTime = System.currentTimeMillis() - startTime;
                    callBack.onSuccess();
                });

    }

    public static void updateScore(List<Type> typeList){
        ExamViewBean constantExamBean = ConstantBean.Companion.getConstantExamBean();
        int sortIndexOrder=1;
        int typeIndex=1;
        int index=0;
        List<Item> reTrainData=new ArrayList<>();
        for (Type type:typeList){
            for (Ques ques:type.getQuesList()){
                for (Child chid:ques.getChildList()){
                    reTrainData.addAll(chid.getItemList());
                }
            }
        }
        for (Type type:constantExamBean.getTypeList()){
            type.setTypeIndex(typeIndex);
            typeIndex++;
            float typeScore=0f;
            boolean isWaitScore=true;
            for (Ques ques:type.getQuesList()){
                List<SortIndex> sortIndexList=new ArrayList<>();

                for (Child child:ques.getChildList()){
                    for (Item item:child.getItemList()){
                        SortIndex sortIndex=new SortIndex();
                        if(index>=reTrainData.size()){

                        }else{
                            Item quesPointScoreInfo = reTrainData.get(index);
                            item.setEvalScore(quesPointScoreInfo.getEvalScore());
                            index++;
                            float totalScore = item.getTotalScore();
                            if(totalScore>0){
                                float rate=quesPointScoreInfo.getEvalScore()/totalScore;
                                item.setScoreRate(rate);
                                item.setTotalScore(totalScore);

                            }
                            sortIndex.setState(quesPointScoreInfo.getEvalScore()<0?0:2);
                            if(quesPointScoreInfo.getComment()!=null){
                                item.setComment(quesPointScoreInfo.getComment());
                                item.setDetailComment(quesPointScoreInfo.getDetailComment());
                            }
                        }
                        sortIndex.setNewSortIndex(sortIndexOrder+"");
                        sortIndex.setScoreRate((double) item.getScoreRate());
                        sortIndexList.add(sortIndex);
                        sortIndexOrder++;
                        if(item.getEvalScore()>=0){
                            typeScore+=item.getEvalScore();
                            isWaitScore=false;
                        }
                    }
                }
                ques.setSortIndexList(sortIndexList);
            }
            if(isWaitScore){
                type.setEvalScore("--");
            }else{
                type.setEvalScore(typeScore+"");
            }
        }
    }

    private static boolean hasText(String htmlString) {
        String regularExpression = "<[^>]+>";
        Pattern pattern = Pattern.compile(regularExpression, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(htmlString);
        String tmp = matcher.replaceAll("").trim();
        return tmp.length() > 0;
    }
}
